package app.itgungnir.compose.wan.business.login

import androidx.lifecycle.ViewModel
import app.itgungnir.compose.wan.utils.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow

class LoginViewModel : ViewModel() {

    val loadingState = MutableStateFlow(false)
    val errorState = MutableSharedFlow<Throwable?>()
    var loadingJob: Job? = null

    val loginSuccessState = MutableSharedFlow<Boolean>()

    /**
     * 用户登录
     */
    fun login(userName: String, password: String) = launch(loadingState, errorState) {
        if (userName.isEmpty()) {
            errorState.emit(IllegalArgumentException("用户名不能为空！"))
            return@launch
        }
        if (password.isEmpty()) {
            errorState.emit(IllegalArgumentException("密码不能为空！"))
            return@launch
        }
        wanAndroidService.login(userName = userName, password = password).wanResponse<UserBaseInfo>()?.let { response ->
            LocalDataStore.updateLocalData {
                it.userInfo = app.itgungnir.compose.wan.UserInfo.newBuilder().apply {
                    this.id = response.id
                    this.name = response.publicName ?: response.nickname ?: response.username ?: ""
                }.build()
            }
            response.collectIds?.takeIf { it.isNotEmpty() }?.forEach { id ->
                WanDatabase.instance.dao().updateHomeArticleCollect(id, true)
            }
            loginSuccessState.emit(true)
        }
    }.also { loadingJob = it }
}
